"""
环境卫生管理相关的API端点
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, UploadFile, File
from fastapi.responses import JSONResponse
import cv2
import numpy as np

from schemas.hygiene_management import (
    WasteAnalysisResult, WasteDetectionConfig, CleanlinessAssessment, 
    CleanlinessConfig, CleaningTask, CleaningTaskStatus, CleaningTaskPriority,
    CleaningEfficiencyMetrics, HygieneZone, HygieneIssue, WasteType
)
from services.campus_environment_hygiene.waste_detection_service import waste_detection_service
from services.cleanliness_assessment_service import cleanliness_assessment_service
from services.cleaning_efficiency_service import cleaning_efficiency_service
from core.auth import get_current_user
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()

router = APIRouter()


# 垃圾检测相关端点
@router.post("/waste/analyze", response_model=WasteAnalysisResult)
async def analyze_waste(
    camera_id: str,
    file: UploadFile = File(...),
    zone_id: Optional[str] = None,
    current_user: dict = Depends(get_current_user)
):
    """垃圾检测分析"""
    try:
        # 读取上传的图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 执行垃圾检测
        result = await waste_detection_service.analyze_waste(image, camera_id, zone_id)
        
        return result
        
    except Exception as e:
        logger.error(f"Waste analysis failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/waste/results")
async def get_waste_analysis_results(
    camera_id: Optional[str] = None,
    zone_id: Optional[str] = None,
    waste_type: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取垃圾分析结果"""
    try:
        waste_type_enum = WasteType(waste_type) if waste_type else None
        
        results = await waste_detection_service.get_analysis_results(
            camera_id=camera_id,
            zone_id=zone_id,
            waste_type=waste_type_enum,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return results
    except Exception as e:
        logger.error(f"Failed to get waste analysis results: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/waste/statistics")
async def get_waste_statistics(
    hours: int = 24,
    current_user: dict = Depends(get_current_user)
):
    """获取垃圾统计"""
    try:
        time_range = timedelta(hours=hours)
        stats = waste_detection_service.get_waste_statistics(time_range)
        return stats
    except Exception as e:
        logger.error(f"Failed to get waste statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/waste/issues")
async def get_hygiene_issues(
    camera_id: Optional[str] = None,
    zone_id: Optional[str] = None,
    issue_type: Optional[str] = None,
    is_resolved: Optional[bool] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取卫生问题"""
    try:
        from schemas.hygiene_management import HygieneIssueType
        issue_type_enum = HygieneIssueType(issue_type) if issue_type else None
        
        issues = await waste_detection_service.get_hygiene_issues(
            camera_id=camera_id,
            zone_id=zone_id,
            issue_type=issue_type_enum,
            is_resolved=is_resolved,
            limit=limit
        )
        return issues
    except Exception as e:
        logger.error(f"Failed to get hygiene issues: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/waste/issues/{issue_id}/resolve")
async def resolve_hygiene_issue(
    issue_id: str,
    resolution_notes: str = "",
    current_user: dict = Depends(get_current_user)
):
    """解决卫生问题"""
    try:
        success = await waste_detection_service.resolve_issue(issue_id, resolution_notes)
        if not success:
            raise HTTPException(status_code=404, detail="Issue not found")
        
        return {"message": "Issue resolved", "issue_id": issue_id}
    except Exception as e:
        logger.error(f"Failed to resolve issue: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 清洁度评估相关端点
@router.post("/cleanliness/assess", response_model=CleanlinessAssessment)
async def assess_cleanliness(
    camera_id: str,
    zone_id: str,
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user)
):
    """清洁度评估"""
    try:
        # 读取上传的图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 执行清洁度评估
        assessment = await cleanliness_assessment_service.assess_image_cleanliness(
            image, camera_id, zone_id
        )
        
        return assessment
        
    except Exception as e:
        logger.error(f"Cleanliness assessment failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/assessments")
async def get_cleanliness_assessments(
    camera_id: Optional[str] = None,
    zone_id: Optional[str] = None,
    cleanliness_level: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取清洁度评估结果"""
    try:
        from schemas.hygiene_management import CleanlinessLevel
        level_enum = CleanlinessLevel(cleanliness_level) if cleanliness_level else None
        
        assessments = await cleanliness_assessment_service.get_assessments(
            camera_id=camera_id,
            zone_id=zone_id,
            cleanliness_level=level_enum,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return assessments
    except Exception as e:
        logger.error(f"Failed to get cleanliness assessments: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanliness/compare")
async def compare_zones(
    zone_ids: List[str],
    days: int = 7,
    current_user: dict = Depends(get_current_user)
):
    """对比多个区域的卫生状况"""
    try:
        time_range = timedelta(days=days)
        comparison = await cleanliness_assessment_service.compare_zones(zone_ids, time_range)
        return comparison
    except Exception as e:
        logger.error(f"Failed to compare zones: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/zones")
async def get_hygiene_zones(
    current_user: dict = Depends(get_current_user)
):
    """获取卫生区域"""
    try:
        zones = cleanliness_assessment_service.get_zones()
        return zones
    except Exception as e:
        logger.error(f"Failed to get hygiene zones: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanliness/zones")
async def add_hygiene_zone(
    zone: HygieneZone,
    current_user: dict = Depends(get_current_user)
):
    """添加卫生区域"""
    try:
        cleanliness_assessment_service.add_zone(zone)
        return {"message": "Zone added", "zone_id": zone.zone_id}
    except Exception as e:
        logger.error(f"Failed to add hygiene zone: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/statistics")
async def get_cleanliness_statistics(
    current_user: dict = Depends(get_current_user)
):
    """获取清洁度统计"""
    try:
        stats = cleanliness_assessment_service.get_statistics()
        return stats
    except Exception as e:
        logger.error(f"Failed to get cleanliness statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 清洁任务管理相关端点
@router.post("/cleaning/tasks", response_model=CleaningTask)
async def create_cleaning_task(
    title: str,
    description: str,
    zone_id: str,
    camera_id: str,
    priority: str = "medium",
    estimated_duration: Optional[int] = None,
    related_issues: List[str] = None,
    current_user: dict = Depends(get_current_user)
):
    """创建清洁任务"""
    try:
        priority_enum = CleaningTaskPriority(priority)
        
        task = await cleaning_efficiency_service.create_cleaning_task(
            title=title,
            description=description,
            zone_id=zone_id,
            camera_id=camera_id,
            priority=priority_enum,
            estimated_duration=estimated_duration,
            related_issues=related_issues or []
        )
        
        return task
        
    except Exception as e:
        logger.error(f"Failed to create cleaning task: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleaning/tasks")
async def get_cleaning_tasks(
    status: Optional[str] = None,
    zone_id: Optional[str] = None,
    assigned_to: Optional[str] = None,
    priority: Optional[str] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取清洁任务"""
    try:
        status_enum = CleaningTaskStatus(status) if status else None
        priority_enum = CleaningTaskPriority(priority) if priority else None
        
        tasks = await cleaning_efficiency_service.get_cleaning_tasks(
            status=status_enum,
            zone_id=zone_id,
            assigned_to=assigned_to,
            priority=priority_enum,
            limit=limit
        )
        return tasks
    except Exception as e:
        logger.error(f"Failed to get cleaning tasks: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleaning/tasks/{task_id}/start")
async def start_cleaning_task(
    task_id: str,
    cleaner_id: str,
    current_user: dict = Depends(get_current_user)
):
    """开始清洁任务"""
    try:
        success = await cleaning_efficiency_service.start_cleaning_task(task_id, cleaner_id)
        if not success:
            raise HTTPException(status_code=404, detail="Task not found or cannot be started")
        
        return {"message": "Task started", "task_id": task_id}
    except Exception as e:
        logger.error(f"Failed to start cleaning task: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleaning/tasks/{task_id}/complete")
async def complete_cleaning_task(
    task_id: str,
    before_image: Optional[UploadFile] = File(None),
    after_image: Optional[UploadFile] = File(None),
    tools_used: List[str] = None,
    notes: str = "",
    current_user: dict = Depends(get_current_user)
):
    """完成清洁任务"""
    try:
        before_img = None
        after_img = None
        
        # 处理清洁前图像
        if before_image:
            before_data = await before_image.read()
            before_nparr = np.frombuffer(before_data, np.uint8)
            before_img = cv2.imdecode(before_nparr, cv2.IMREAD_COLOR)
        
        # 处理清洁后图像
        if after_image:
            after_data = await after_image.read()
            after_nparr = np.frombuffer(after_data, np.uint8)
            after_img = cv2.imdecode(after_nparr, cv2.IMREAD_COLOR)
        
        # 完成任务并评估效率
        metrics = await cleaning_efficiency_service.complete_cleaning_task(
            task_id=task_id,
            before_image=before_img,
            after_image=after_img,
            tools_used=tools_used or [],
            notes=notes
        )
        
        if not metrics:
            raise HTTPException(status_code=404, detail="Task not found or cannot be completed")
        
        return {
            "message": "Task completed",
            "task_id": task_id,
            "efficiency_metrics": metrics
        }
        
    except Exception as e:
        logger.error(f"Failed to complete cleaning task: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleaning/efficiency")
async def get_efficiency_metrics(
    cleaner_id: Optional[str] = None,
    zone_id: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取清洁效率指标"""
    try:
        metrics = await cleaning_efficiency_service.get_efficiency_metrics(
            cleaner_id=cleaner_id,
            zone_id=zone_id,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return metrics
    except Exception as e:
        logger.error(f"Failed to get efficiency metrics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleaning/schedule")
async def generate_cleaning_schedule(
    available_cleaners: int = 3,
    time_horizon_hours: int = 8,
    current_user: dict = Depends(get_current_user)
):
    """生成清洁调度计划"""
    try:
        schedule = await cleaning_efficiency_service.generate_cleaning_schedule(
            available_cleaners=available_cleaners,
            time_horizon_hours=time_horizon_hours
        )
        return {
            "schedule": schedule,
            "total_tasks": len(schedule),
            "available_cleaners": available_cleaners,
            "time_horizon_hours": time_horizon_hours
        }
    except Exception as e:
        logger.error(f"Failed to generate cleaning schedule: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleaning/schedules")
async def get_cleaning_schedules(
    limit: int = 10,
    current_user: dict = Depends(get_current_user)
):
    """获取清洁调度计划"""
    try:
        schedules = cleaning_efficiency_service.get_cleaning_schedules(limit)
        return schedules
    except Exception as e:
        logger.error(f"Failed to get cleaning schedules: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleaning/recommendations/{zone_id}")
async def get_cleaning_recommendations(
    zone_id: str,
    current_user: dict = Depends(get_current_user)
):
    """获取清洁建议"""
    try:
        recommendations = await cleaning_efficiency_service.get_cleaning_recommendations(zone_id)
        return {
            "zone_id": zone_id,
            "recommendations": recommendations
        }
    except Exception as e:
        logger.error(f"Failed to get cleaning recommendations: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleaning/statistics")
async def get_cleaning_statistics(
    current_user: dict = Depends(get_current_user)
):
    """获取清洁统计"""
    try:
        stats = cleaning_efficiency_service.get_statistics()
        return stats
    except Exception as e:
        logger.error(f"Failed to get cleaning statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 服务管理端点
@router.post("/services/waste-detection/start")
async def start_waste_detection_service(
    current_user: dict = Depends(get_current_user)
):
    """启动垃圾检测服务"""
    try:
        await waste_detection_service.start_service()
        return {"message": "Waste detection service started"}
    except Exception as e:
        logger.error(f"Failed to start waste detection service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/waste-detection/stop")
async def stop_waste_detection_service(
    current_user: dict = Depends(get_current_user)
):
    """停止垃圾检测服务"""
    try:
        await waste_detection_service.stop_service()
        return {"message": "Waste detection service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop waste detection service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/cleanliness-assessment/start")
async def start_cleanliness_service(
    current_user: dict = Depends(get_current_user)
):
    """启动清洁度评估服务"""
    try:
        await cleanliness_assessment_service.start_service()
        return {"message": "Cleanliness assessment service started"}
    except Exception as e:
        logger.error(f"Failed to start cleanliness service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/cleanliness-assessment/stop")
async def stop_cleanliness_service(
    current_user: dict = Depends(get_current_user)
):
    """停止清洁度评估服务"""
    try:
        await cleanliness_assessment_service.stop_service()
        return {"message": "Cleanliness assessment service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop cleanliness service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/cleaning-efficiency/start")
async def start_cleaning_efficiency_service(
    current_user: dict = Depends(get_current_user)
):
    """启动保洁效率服务"""
    try:
        await cleaning_efficiency_service.start_service()
        return {"message": "Cleaning efficiency service started"}
    except Exception as e:
        logger.error(f"Failed to start cleaning efficiency service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/cleaning-efficiency/stop")
async def stop_cleaning_efficiency_service(
    current_user: dict = Depends(get_current_user)
):
    """停止保洁效率服务"""
    try:
        await cleaning_efficiency_service.stop_service()
        return {"message": "Cleaning efficiency service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop cleaning efficiency service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 配置管理端点
@router.get("/config/waste-detection", response_model=WasteDetectionConfig)
async def get_waste_detection_config(
    current_user: dict = Depends(get_current_user)
):
    """获取垃圾检测配置"""
    try:
        config = waste_detection_service.get_config()
        return config
    except Exception as e:
        logger.error(f"Failed to get waste detection config: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/config/waste-detection")
async def update_waste_detection_config(
    config: WasteDetectionConfig,
    current_user: dict = Depends(get_current_user)
):
    """更新垃圾检测配置"""
    try:
        waste_detection_service.update_config(config)
        return {"message": "Waste detection config updated"}
    except Exception as e:
        logger.error(f"Failed to update waste detection config: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/config/cleanliness", response_model=CleanlinessConfig)
async def get_cleanliness_config(
    current_user: dict = Depends(get_current_user)
):
    """获取清洁度评估配置"""
    try:
        config = cleanliness_assessment_service.get_config()
        return config
    except Exception as e:
        logger.error(f"Failed to get cleanliness config: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/config/cleanliness")
async def update_cleanliness_config(
    config: CleanlinessConfig,
    current_user: dict = Depends(get_current_user)
):
    """更新清洁度评估配置"""
    try:
        cleanliness_assessment_service.update_config(config)
        return {"message": "Cleanliness config updated"}
    except Exception as e:
        logger.error(f"Failed to update cleanliness config: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 模型训练和管理端点
@router.post("/waste/model/training-data")
async def add_training_sample(
    camera_id: str,
    file: UploadFile = File(...),
    annotations: str = "",  # JSON格式的标注数据
    image_id: Optional[str] = None,
    current_user: dict = Depends(get_current_user)
):
    """添加训练样本"""
    try:
        # 读取图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 解析标注数据
        import json
        if annotations:
            annotation_data = json.loads(annotations)
            # 转换为WasteDetection格式
            detections = []
            for ann in annotation_data:
                from schemas.hygiene_management import WasteDetection
                detection = WasteDetection(
                    detection_id=str(uuid4()),
                    waste_type=WasteType(ann['waste_type']),
                    confidence=ann.get('confidence', 1.0),
                    bounding_box=ann['bounding_box'],
                    area=(ann['bounding_box'][2] - ann['bounding_box'][0]) * 
                         (ann['bounding_box'][3] - ann['bounding_box'][1]),
                    location=((ann['bounding_box'][0] + ann['bounding_box'][2]) / 2,
                             (ann['bounding_box'][1] + ann['bounding_box'][3]) / 2),
                    timestamp=datetime.now(),
                    camera_id=camera_id
                )
                detections.append(detection)
        else:
            detections = []
        
        # 添加训练样本
        sample_id = await waste_detection_service.add_training_sample(
            image, detections, image_id
        )
        
        return {
            "message": "Training sample added",
            "sample_id": sample_id,
            "detections_count": len(detections)
        }
        
    except Exception as e:
        logger.error(f"Failed to add training sample: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/waste/model/create-dataset")
async def create_training_dataset(
    samples_data: List[Dict[str, Any]],
    current_user: dict = Depends(get_current_user)
):
    """创建训练数据集"""
    try:
        dataset_stats = await waste_detection_service.create_training_dataset(samples_data)
        return {
            "message": "Training dataset created",
            "dataset_statistics": dataset_stats
        }
    except Exception as e:
        logger.error(f"Failed to create training dataset: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/waste/model/train")
async def train_waste_model(
    background_tasks: BackgroundTasks,
    training_config: Optional[Dict[str, Any]] = None,
    current_user: dict = Depends(get_current_user)
):
    """训练垃圾检测模型"""
    try:
        # 在后台任务中执行训练
        background_tasks.add_task(
            _background_model_training,
            training_config or {}
        )
        
        return {
            "message": "Model training started in background",
            "status": "training_started"
        }
        
    except Exception as e:
        logger.error(f"Failed to start model training: {e}")
        raise HTTPException(status_code=500, detail=str(e))


async def _background_model_training(training_config: Dict[str, Any]):
    """后台模型训练任务"""
    try:
        logger.info("Starting background model training")
        result = await waste_detection_service.train_custom_model(training_config)
        logger.info(f"Model training completed: {result['training_id']}")
    except Exception as e:
        logger.error(f"Background model training failed: {e}")


@router.post("/waste/model/validate")
async def validate_model(
    model_path: Optional[str] = None,
    confidence_threshold: float = 0.5,
    current_user: dict = Depends(get_current_user)
):
    """验证模型精度"""
    try:
        validation_result = await waste_detection_service.validate_model_accuracy(
            model_path, confidence_threshold
        )
        return validation_result
    except Exception as e:
        logger.error(f"Failed to validate model: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/waste/model/load")
async def load_custom_model(
    model_path: str,
    current_user: dict = Depends(get_current_user)
):
    """加载自定义模型"""
    try:
        await waste_detection_service.load_custom_model(model_path)
        return {
            "message": "Custom model loaded successfully",
            "model_path": model_path
        }
    except Exception as e:
        logger.error(f"Failed to load custom model: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/waste/model/report")
async def get_model_report(
    current_user: dict = Depends(get_current_user)
):
    """获取模型报告"""
    try:
        report = await waste_detection_service.get_model_report()
        return report
    except Exception as e:
        logger.error(f"Failed to get model report: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/waste/model/statistics")
async def get_model_statistics(
    current_user: dict = Depends(get_current_user)
):
    """获取模型统计信息"""
    try:
        stats = waste_detection_service.get_model_statistics()
        return stats
    except Exception as e:
        logger.error(f"Failed to get model statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/waste/model/export-data")
async def export_training_data(
    output_path: str,
    current_user: dict = Depends(get_current_user)
):
    """导出训练数据"""
    try:
        export_info = await waste_detection_service.export_training_data(output_path)
        return export_info
    except Exception as e:
        logger.error(f"Failed to export training data: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 清洁标准管理端点
@router.post("/cleanliness/standards")
async def create_cleanliness_standard(
    standard_data: Dict[str, Any],
    current_user: dict = Depends(get_current_user)
):
    """创建清洁标准"""
    try:
        # 验证标准数据
        validation_errors = cleanliness_assessment_service.validate_cleanliness_standard(standard_data)
        if validation_errors:
            raise HTTPException(status_code=400, detail=f"Validation errors: {validation_errors}")
        
        standard_id = cleanliness_assessment_service.create_cleanliness_standard(standard_data)
        return {
            "message": "Cleanliness standard created",
            "standard_id": standard_id
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Failed to create cleanliness standard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/standards")
async def get_cleanliness_standards(
    zone_type: Optional[str] = None,
    current_user: dict = Depends(get_current_user)
):
    """获取清洁标准"""
    try:
        if zone_type:
            standards = cleanliness_assessment_service.get_standards_by_zone_type(zone_type)
        else:
            standards = cleanliness_assessment_service.get_all_cleanliness_standards()
        
        return {
            "standards": standards,
            "total": len(standards)
        }
    except Exception as e:
        logger.error(f"Failed to get cleanliness standards: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/standards/{standard_id}")
async def get_cleanliness_standard(
    standard_id: str,
    current_user: dict = Depends(get_current_user)
):
    """获取指定清洁标准"""
    try:
        standard = cleanliness_assessment_service.get_cleanliness_standard(standard_id)
        if not standard:
            raise HTTPException(status_code=404, detail="Cleanliness standard not found")
        
        return standard
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get cleanliness standard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/cleanliness/standards/{standard_id}")
async def update_cleanliness_standard(
    standard_id: str,
    updates: Dict[str, Any],
    current_user: dict = Depends(get_current_user)
):
    """更新清洁标准"""
    try:
        success = cleanliness_assessment_service.update_cleanliness_standard(standard_id, updates)
        if not success:
            raise HTTPException(status_code=404, detail="Cleanliness standard not found")
        
        return {"message": "Cleanliness standard updated"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to update cleanliness standard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/cleanliness/standards/{standard_id}")
async def delete_cleanliness_standard(
    standard_id: str,
    current_user: dict = Depends(get_current_user)
):
    """删除清洁标准"""
    try:
        success = cleanliness_assessment_service.delete_cleanliness_standard(standard_id)
        if not success:
            raise HTTPException(status_code=404, detail="Cleanliness standard not found")
        
        return {"message": "Cleanliness standard deleted"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to delete cleanliness standard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanliness/standards/validate")
async def validate_cleanliness_standard(
    standard_data: Dict[str, Any],
    current_user: dict = Depends(get_current_user)
):
    """验证清洁标准"""
    try:
        validation_errors = cleanliness_assessment_service.validate_cleanliness_standard(standard_data)
        
        return {
            "valid": len(validation_errors) == 0,
            "errors": validation_errors
        }
    except Exception as e:
        logger.error(f"Failed to validate cleanliness standard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanliness/zones/{zone_id}/assign-standard")
async def assign_standard_to_zone(
    zone_id: str,
    standard_id: str,
    current_user: dict = Depends(get_current_user)
):
    """为区域分配清洁标准"""
    try:
        success = cleanliness_assessment_service.assign_standard_to_zone(zone_id, standard_id)
        if not success:
            raise HTTPException(status_code=400, detail="Failed to assign standard to zone")
        
        return {"message": f"Standard {standard_id} assigned to zone {zone_id}"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to assign standard to zone: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/zones/{zone_id}/standard")
async def get_zone_cleanliness_standard(
    zone_id: str,
    current_user: dict = Depends(get_current_user)
):
    """获取区域的清洁标准"""
    try:
        standard = cleanliness_assessment_service.get_zone_cleanliness_standard(zone_id)
        if not standard:
            raise HTTPException(status_code=404, detail="No cleanliness standard assigned to this zone")
        
        return standard
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to get zone cleanliness standard: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/zones/{zone_id}/compliance")
async def assess_zone_compliance(
    zone_id: str,
    days: int = 7,
    current_user: dict = Depends(get_current_user)
):
    """评估区域合规性"""
    try:
        compliance = await cleanliness_assessment_service.assess_zone_compliance(zone_id, days)
        return compliance
    except Exception as e:
        logger.error(f"Failed to assess zone compliance: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/cleanliness/standards/statistics")
async def get_standards_statistics(
    current_user: dict = Depends(get_current_user)
):
    """获取清洁标准统计信息"""
    try:
        stats = cleanliness_assessment_service.get_standards_statistics()
        return stats
    except Exception as e:
        logger.error(f"Failed to get standards statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanliness/standards/export")
async def export_cleanliness_standards(
    file_path: str,
    current_user: dict = Depends(get_current_user)
):
    """导出清洁标准"""
    try:
        success = cleanliness_assessment_service.export_cleanliness_standards(file_path)
        if not success:
            raise HTTPException(status_code=500, detail="Failed to export standards")
        
        return {"message": f"Standards exported to {file_path}"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Failed to export standards: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanliness/standards/import")
async def import_cleanliness_standards(
    file_path: str,
    overwrite: bool = False,
    current_user: dict = Depends(get_current_user)
):
    """导入清洁标准"""
    try:
        result = cleanliness_assessment_service.import_cleanliness_standards(file_path, overwrite)
        return {
            "message": "Standards import completed",
            "result": result
        }
    except Exception as e:
        logger.error(f"Failed to import standards: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 健康检查端点
@router.get("/health")
async def health_check():
    """健康检查"""
    try:
        status = {
            "waste_detection": "healthy",
            "cleanliness_assessment": "healthy",
            "cleaning_efficiency": "healthy",
            "timestamp": datetime.now().isoformat()
        }
        
        return status
        
    except Exception as e:
        logger.error(f"Health check failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))